﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Soft.Xml
{
    public class BaseConfigFile : BaseXml
    {

        /// <summary>
        /// 检查文件是否存在
        /// </summary>
        /// <param name="fileName">xml文件名称</param>
        /// <param name="rootNodeName">节点名称</param>
        public BaseConfigFile(string fileName, string rootNodeName = "Configuration")
        {
            if (string.IsNullOrWhiteSpace(fileName))
            {
                throw new ArgumentNullException("fileName");
            }
            if (!fileName.CheckFileName(false))
            {
                throw new FormatException("文件名：" + fileName + " 格式错误。");
            }
            this.mFileName = FactoryAdvisorPlatformGlobalSet.ApplicationPath + fileName;
            this.ROOT_NAME = (rootNodeName ?? this.ROOT_NAME);
        }


        /// <summary>
        /// 初始化
        /// </summary>
        protected override void Initialize()
        {
            base.Initialize();
            if (base.DocumentElement == null)
            {
                base.GetElement(this, this.ROOT_NAME, true);
                return;
            }
            if (string.Compare(base.DocumentElement.Name, this.ROOT_NAME, true) != 0)
            {
                throw new Exception("本地业务服务配置文件格式错误：根节点不是目标节点（" + this.ROOT_NAME + "）。");
            }
        }


        /// <summary>
        /// 加载文件
        /// </summary>
        public void Load()
        {
            base.Load(this.mFileName);
        }


        /// <summary>
        /// 保存文件
        /// </summary>
        public void Save()
        {
            base.Save(this.mFileName);
        }


        /// <summary>
        /// 根据节点的值 获取对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="nodeName"></param>
        /// <returns></returns>
        protected virtual T GetObjectElement<T>(string nodeName) where T : BaseSubElement
        {
            return (T)((object)Activator.CreateInstance(typeof(T), new object[]
            {
                base.GetElement(base.DocumentElement, nodeName, true)
            }));
        }


        /// <summary>
        /// 根节点的名称
        /// </summary>
        private readonly string ROOT_NAME = "Configuration";


        /// <summary>
        /// 文件的名称
        /// </summary>
        private readonly string mFileName;


    }
}
